package com.example.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.mapper.OperateLogMapper;
import com.example.pojo.OperateLog;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.http.HttpRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect//切面类
public class LogAspect {
    @Autowired
    private HttpServletRequest request;//拿到当前的对象
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.example.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable{

        //操作人id
        //获取请求头中的jwt令牌，解析令牌
        String jwt = request.getHeader("token");
        // 解析JWT，获取其中的声明
        Claims claims=JwtUtils.parseJwt(jwt);
        Integer operateUser = (Integer) claims.get("id");

        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //操作类名
        String className = joinPoint.getTarget().getClass().getName();
        //操作方法名
        var methodName = joinPoint.getSignature().getName();
        //操作方法参数
        Object[] args=joinPoint.getArgs();
        var methodParams = Arrays.toString(args);
        var begin = System.currentTimeMillis();
        //调用原始目标方法运行
        Object result = joinPoint.proceed();
        var end = System.currentTimeMillis();
        //操作方法返回值
        var returnValue = JSONObject.toJSONString(result);
        //操作耗时
        var costTime = end - begin;

        //记录日志
        OperateLog operateLog = new OperateLog(null, operateUser, operateTime, className, methodName, methodParams, returnValue, costTime);
        //operateLog可以获取/设置id,时间等
        operateLogMapper.insert(operateLog);
        return result;
    }
}
